using UnityEngine;

public class PlayerCounterAttackState : PlayerState
{
    private static readonly int SuccessfulCounterAttack = Animator.StringToHash("successfulCounterAttack");
    private bool canCreate;

    public PlayerCounterAttackState(Player player, string animBoolName) : base(player, animBoolName) { }

    public override void Enter()
    {
        base.Enter();
        canCreate = true;
        stateTimer = player.counterAttackDuration;
        player.Anim.SetBool(SuccessfulCounterAttack, false);
    }

    public override void Update()
    {
        base.Update();
        player.SetVelocityToZero();
        Collider2D[] results = new Collider2D[20];
        var size = Physics2D.OverlapCircleNonAlloc(player.AttackPoint.position, player.attackCheckRadius, results);
        for (int i = 0; i < size; i++)
        {
            if (results[i].TryGetComponent(out ArrowController arrow))
            {
                arrow.Flip();
                SuccessfullCounterAttack();
            }
            if (!results[i].TryGetComponent(out Enemy hit) || !hit.CanBeStunned()) continue;
            SuccessfullCounterAttack();
            skillManager.Parry.Use(); // going to use to restore health on parry
            if (!canCreate) continue;
            canCreate = false;
            player.SkillManager.Parry.MakeMirageOnParry(hit.transform);
        }
        if (stateTimer < 0 || triggerCalled)
        {
            StateMachine.ChangeState(player.IdleState);
        }
    }

    private void SuccessfullCounterAttack()
    {
        stateTimer = 10f; // any value greater than 0
        player.Anim.SetBool(SuccessfulCounterAttack, true);
    }
}